package com.kangaroo.myhome.controller;

import com.kangaroo.myhome.model.TSysFile;
import com.kangaroo.myhome.service.impl.FileService;
import com.kangaroo.myhome.utils.SecurityUtils;
import com.kangaroo.myhome.vo.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName UploadController
 * @Description TODO
 * @Author kangaroo
 * @Date 2020/8/2 17:24
 * @Version 1.0
 **/
@Controller
@RequestMapping("upload")
public class UploadController {

    @Value("${file.downPath}")
    private String uploadPath;

    @Autowired
    private FileService fileService;

    // private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping(value = "/findAll")
    public ResponseModel findAll(HttpServletRequest request) {
        ResponseModel model = new ResponseModel();
        String name = request.getParameter("name");
        String projectId = request.getParameter("projectId");
        String pageS = request.getParameter("page");
        String rowsS = request.getParameter("rows");
        int page = Integer.parseInt(pageS);
        int rows = Integer.parseInt(rowsS);
        if (StringUtil.isEmpty(projectId)) {
            model.setCode(201);
            model.setMessage("请选择查看附件的项目");
            return model;
        } else {
            return fileService.findAll(name, projectId, page, rows);
        }
    }

    @GetMapping(value = "/delete")
    public ResponseModel delete(HttpServletRequest request) {
        ResponseModel model = new ResponseModel();
        String id = request.getParameter("id");
        if (StringUtil.isEmpty(id)) {
            model.setCode(201);
            model.setMessage("请先选择要删除的附件");
            return model;
        } else {
            return fileService.delete(id);
        }
    }

    @PostMapping("/upload")
    @ResponseBody
    public ResponseModel upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        ResponseModel model = new ResponseModel();
        if (file.isEmpty()) {
            model.setCode(201);
            model.setMessage("请先选择文件再重试");
            return model;
        }
        String projectId = request.getParameter("projectId");
        String stage = request.getParameter("stage");
        if (StringUtil.isEmpty(projectId) || StringUtil.isEmpty(stage)) {
            model.setCode(201);
            model.setMessage("项目为空，请在项目下上传附件");
            return model;
        }

        TSysFile tSysFile = new TSysFile();
        tSysFile.setId(UUID.randomUUID().toString());
        tSysFile.setProjectId(projectId);
        tSysFile.setStage(stage);
        // SecurityUtils.getUsername()
        tSysFile.setCreator(SecurityUtils.getUsername());
        tSysFile.setCreateTime(new Date());

        model = saveFilePhysics(file, tSysFile);

        if (200 == model.getCode()) {
            int insertSuccessNum = fileService.saveFileToBD(tSysFile);
            if (insertSuccessNum > 0) {
                model.setCode(200);
                model.setMessage("附件保存成功！");
                model.setData(tSysFile);
            } else {
                model.setCode(201);
                model.setMessage("附件保存失败");
            }
        }

        return model;
    }

    /**
     * 保存附件
     * 
     * @param file
     * @return
     */
    public ResponseModel saveFilePhysics(MultipartFile file, TSysFile tSysFile) {
        ResponseModel model = new ResponseModel();

        String fileName = file.getOriginalFilename();
        tSysFile.setName(fileName);
        String folderPath = uploadPath;
        long fileNameSubLong = new Date().getTime();
        String fileRelativePath = "insp/file/" + fileNameSubLong + fileName;
        tSysFile.setPath(fileRelativePath);

        // 创建上传文件目录
        File folder = new File(folderPath);
        // 如果文件夹不存在创建对应的文件夹
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 设置文件名
        String savePath = folderPath + File.separator + fileNameSubLong + fileName;

        File dest = new File(savePath);

        try {
            file.transferTo(dest);
            model.setCode(200);
            model.setMessage("附件上传成功");
            Map fileInfo = new HashMap();
            fileInfo.put("fileName", fileName);
            fileInfo.put("fileRelativePath", fileRelativePath);
            model.setData(fileInfo);
            return model;
        } catch (IOException e) {
            // LOGGER.error(e.toString(), e);
            model.setMessage(e.getMessage());
        }
        model.setCode(201);
        return model;
    }

}
